import { createSlice } from "@reduxjs/toolkit";

const counter = createSlice({
  name: "counter",
  initialState: {
    count: 0,
    list: [],
  },
  // built-in immutable.js、redux-thunk
  reducers: {
    increment(state, action) {
      state.count++;
    },
    decrement(state) {
      state.count--;
    },
    push(state) {
      state.list.push(Math.floor(Math.random() * 100));
    },
    splice(state, action) {
      state.list.splice(action.payload, 1);
    },
  },
});

// reducer
export default counter.reducer;

// action
export const { increment, decrement, push, splice } = counter.actions;

// async action
export const decrementAsync = (payload) => {
  return (dispatch, getState) => {
    setTimeout(() => {
      dispatch(decrement());
    }, 2000);
  };
};
